#!/usr/bin/env ruby


#define some useful array functions
class Array 
  def sum
    inject( 0 ) { |sum,x| sum+x }
  end
  def sum_square
    inject( 0 ) { |sum,x| sum+x*x }
  end
  def mean
    sum / size
  end
  def *(other) # dot product
    ret = []
    return nil if !other.is_a? Array || size != other.size
    self.each_with_index {|x, i| ret << x * other[i]}
    ret.sum
  end
end

#calculate the pearson's correlation
def pcor(x,y)
  if x.length != y.length
    raise "arrays must be the same length"
  end

  sumx = x.sum
  sumy  = y.sum

  num = (x.size * (x*y)) - (sumx * sumy)
  den = Math.sqrt((x.size * x.sum_square) - sumx * sumx) * Math.sqrt((y.size * y.sum_square) - sumy * sumy)
  
  if den == 0
    return 0
  end
  
  return num/den
end

